package com.ice.body.rpc.api;

import com.arcsoft.face.FaceFeature;
import com.ice.base.controller.BaseController;
import com.ice.base.model.SysLoginModel;
import com.ice.base.result.AjaxResult;
import com.ice.base.result.ResponseResult;
import com.ice.base.service.SysLoginService;
import com.ice.base.util.BaseUtil;
import com.ice.base.util.FaceEngineTool;
import com.ice.base.util.RedisUtil;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.business.service.ReagentStockService;
import com.ice.body.hardware.model.DeviceFace;
import com.ice.body.hardware.model.DeviceMachine;
import com.ice.body.hardware.service.DeviceMachineService;
import com.ice.body.hardware.service.FaceToRoomService;
import com.ice.body.rpc.dto.ReagentStockDto;
import com.ice.body.rpc.dto.WeighLog;
import com.ice.body.rpc.service.WeighLogService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * Created with GuoYanBin.
 * Description:
 * Date: 2021-11-09
 * Time: 04:03
 */
@RestController
@ApiIgnore(value = "rpc接口-危化品柜")
@RequestMapping("/rpcCabinet")
@Slf4j
public class RpcCabinetApi extends BaseController{
    //---------------------------库存试剂-----------------------start
 
    @Resource
    private ReagentStockService reagentStockService;
    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private WeighLogService weighLogService;
    @Autowired
    private FaceEngineTool faceEngineTool;
    @Autowired
    private RedisUtil redisUtil;

    public static volatile Boolean process = true;
    public static volatile Boolean cabinet = true;
    /**
     * 上传称重数据
     * @return 868  -68  32
     */
    @ApiOperation(value = "称重平台上传数据")
    @PostMapping("/doWeighLog")
    public AjaxResult<T> doWeighLog(@RequestBody WeighLog model) {
        log.info("rpc---称重记录~~~epcCode:"+ model.getEpcCode() +",重量：" +model.getWeight());
        AjaxResult r = AjaxResult.success();

        try{
            model.setCreateTime(new Date());
            weighLogService.insert(model);
            //修改称重重量
            ReagentStock stock = reagentStockService.getByEpcCode(model.getEpcCode());
            if(null != stock){
                //算出净重
                Double totalWeigh = stock.getTotalWeigh();//总重量
                Double leftWeigh = stock.getLeftWeigh();//净重
                Double weight = model.getWeight();//称重
                if(totalWeigh >0 && leftWeigh>0 && weight >0){
                    double v = totalWeigh - weight;//总重-称重=用掉的量
                    double v1 = leftWeigh - v;//净重-用掉的量 = 剩余的量
                    stock.setLeftWeigh(v1);
                }
                reagentStockService.update(stock);
            }
        }catch (Exception e){
            r = ResponseResult.error();
            e.printStackTrace();
        }
        return r;
    }


    @ApiOperation(value = "柜子-opeType 1入库/2出库/3归还/0销毁")
    @PostMapping("/reagentStock/insert")
    public AjaxResult<ReagentStock> insert_ReagentStock(@RequestBody ReagentStockDto model) {
        String serialNo = model.getSerialNo();
        log.info("rpc---调用出入库接口~~~序列号："+ serialNo);
        try{
            return reagentStockService.cabinetRecord(model);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("操作失败!" + e.getMessage());
        }
    }


    /**
     * 柜子面部识别验证
     * @param img
     * @return
     */
    @RequestMapping("/cabinetMatchFace")
    public AjaxResult<T> cabinetMatchFace(String cabNo, String img) {
        AjaxResult r = AjaxResult.error("处理繁忙");
        if (!cabinet) {
            log.info("。。。。试剂柜面部识别繁忙。。。。");
            return r;
        }
        try {
            //生成jpg图片
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String path = BaseUtil.getVideoPath() + "faceImg/compare/" + sdf.format(new Date()) + ".png";
            //保存图片
            parseLoginFace(img, path);
            //人脸对比
            SysLoginModel u = matchFace(path);
            if (null != u && null!= u.getCardNo() && u.getCardNo().contains(cabNo)) {
                log.info(u.getRealName() + " 虹软面部识别出门!!!");
                return AjaxResult.success(u);
            } else {
                log.info("人脸对比失败-用户不存在或没权限");
                r.setMsg("人脸对比失败-用户不存在或没权限");
            }

        } catch (Exception e) {
            log.info("一体机面部识别结算异常！");
            e.printStackTrace();
        }finally {
            process= true;
        }
        return r;
    }


    private void parseLoginFace(String img, String savePath) {
        try {
            if (img == null) //图像数据为空
                return;
            // System.out.println("开始解码");
            BASE64Decoder decoder = new BASE64Decoder();
            //Base64解码
            img = img.replace("data:image/png;base64,", "");
            byte[] b = decoder.decodeBuffer(img);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    public SysLoginModel matchFace(String savePath) {
        File file = null;
        try {
            file = new File(savePath);
            if (!file.exists()) {
                return null;
            }
            //开始人脸对比
            FaceFeature currentFace = faceEngineTool.pathGetFace(savePath);
            Set<Object> faceKeys = redisUtil.hItem("faceMap");
            for (Object key : faceKeys) {
                FaceFeature faceFeature = (FaceFeature) redisUtil.hget("faceMap", key.toString());
                float score = faceEngineTool.CheckFace(currentFace, faceFeature);
                if (score >= 0.75) {
                    return sysLoginService.selectById(key.toString());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
    }
    /**
     *
     * @param serialNo
     * @return
     */
/*    @ApiOperation(value = "柜子下拉用户列表")
    @PostMapping("/user/getUserList")
    public AjaxResult<ReagentStock> getUserList(@RequestBody String serialNo) {
        log.info("rpc---用户查询~~~serialNo:"+ serialNo);
        AjaxResult r = ResponseResult.success();
        CabinetModel cabinet = cabinetService.getBySerialNo(serialNo);
        if(null == cabinet){
            r = ResponseResult.error();
            r.setMsg("序列号不存在!");
            return  r;
        }
        try{
            CabinetUserPermissionModel model = new CabinetUserPermissionModel();
            model.setSerialNo(serialNo);
            ArrayList<CabinetUserPermissionModel> list = cabinetUserPermissionService.selectListByModel(model);
            r.setData(list);
        }catch (Exception e){
            r = ResponseResult.error();
            e.printStackTrace();
        }
        return r;
    }*/
    /**
     * 查询企业库存中待入库的数据
     * 操作台和柜子下拉时,根据序列号查询公司，然后根据公司id讲所有待入库的数据返回给调用方
     * @param serialNo
     * @return
     */
/*
    @ApiOperation(value = "柜子下拉库存列表")
    @PostMapping("/getStockList")
    public AjaxResult<ReagentStock> getStockList(@RequestBody String serialNo) {
        log.info("rpc---库存查询~~~serialNo:"+ serialNo);
        AjaxResult r = ResponseResult.success();
        CabinetModel cabinet = cabinetService.getBySerialNo(serialNo);
        if(null == cabinet){
            r = ResponseResult.error();
            r.setMsg("序列号不存在!");
            return  r;
        }

        try{
            //查询企业库存中待入库的数据
            List<ReagentStock> list = reagentStockService.getByDeptId(cabinet.getDeptId());
//            List<ReagentStock> list = reagentStockService.getBySerialNo(serialNo);
            r.setData(list);
        }catch (Exception e){
            r = ResponseResult.error();
            e.printStackTrace();
        }
        return r;
    }
*/






    /**
     * 校验用户号返回用户对象 没有则返回空
     * @param
     * @return
     */
  /*  @ApiOperation(value = "校验用户号返回用户对象")
    @PostMapping("/getUserByCard")
    public AjaxResult<ReagentStock> getUserByCard(@RequestBody UserCabinetModel model) {
        log.info("rpc---卡号查询用户~~~serialNo:"+ model.getSerialNo());
        AjaxResult r = ResponseResult.success();
        CabinetModel cabinet = cabinetService.getBySerialNo(model.getSerialNo());
        if(null == cabinet){
            r = ResponseResult.error();
            r.setMsg("序列号不存在!");
            return  r;
        }
        try{
            UserCabinetModel user = new UserCabinetModel();
            user.setDeptId(cabinet.getDeptId());
            //user.setNfc(nfc);
            ArrayList<UserCabinetModel> userCabinetModels = userCabinetService.selectListByModel(user);
            if(CollectionUtil.isNotEmpty(userCabinetModels)){
                r.setData(userCabinetModels.get(0));
            }
        }catch (Exception e){
            r = ResponseResult.error();
            e.printStackTrace();
        }
        return r;
    }*/





    //---------------------------库存试剂-----------------------end
}
